package com.coffee.job.service.quartz.config;

import com.coffee.job.api.quartz.api.QuartzJobService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;

/**
 * 自动扫描job类，并注册到quartz
 *
 * @author Xulg
 * Created in 2019-08-06 10:05
 */
@Component
public class StartJob implements ApplicationListener<ContextRefreshedEvent> {
    private static final Logger logger = LoggerFactory.getLogger(StartJob.class);

    private static final String JOB_BASE_PACKAGE = "com.linggong.task.service.quartz.job";

    @DubboReference(check = false)
    private QuartzJobService quartzJobService;

    /**
     * 容器启动完毕加载job任务
     *
     * @param event the application event
     */
    @SuppressWarnings("unchecked")
    @Override
    public void onApplicationEvent(@Nonnull ContextRefreshedEvent event) {
        // 扫描出所有的Job类
       /* Set<Class<?>> jobClassNameList = new Reflections(JOB_BASE_PACKAGE).getTypesAnnotatedWith(JobInfo.class);
        if (logger.isInfoEnabled()) {
            logger.info("容器启动完毕加载job任务=========扫描到的job的class文件有:\n" + JSON
                    .toJSONString(new ArrayList<>(jobClassNameList), true));
        }

        // 注册Job
        List<String> loadSuccessFullyJobClassNames = new ArrayList<>(jobClassNameList.size());
        List<String> disabledJobClassNames = new ArrayList<>(jobClassNameList.size());
        jobClassNameList.stream().filter(Job.class::isAssignableFrom)
                .map((jobClass) -> (Class<? extends Job>) jobClass)
                .forEach((jobClass) -> {
                    JobInfo jobInfo = jobClass.getAnnotation(JobInfo.class);
                    if (jobInfo.isEnable()) {
                        quartzJobService.addScheduleJob(new TaskDefine(jobInfo.name(),
                                jobInfo.group(), jobInfo.description(), jobInfo.cronExpression(),
                                Maps.newHashMapWithExpectedSize(0), jobClass));
                        loadSuccessFullyJobClassNames.add(jobClass.getName());
                    } else {
                        quartzJobService.pauseJob(jobInfo.name(),jobInfo.group());
                        disabledJobClassNames.add(jobClass.getName());
                    }
                });
        if (logger.isInfoEnabled()) {
            logger.info("容器启动完毕加载job任务=========启用并成功加载的job的class文件有:\n" + JSON
                    .toJSONString(loadSuccessFullyJobClassNames, true));
            logger.info("容器启动完毕加载job任务=========禁止加载的job的class文件有:\n" + JSON
                    .toJSONString(disabledJobClassNames, true));
        }*/
    }
}
